package com.lgy.httpmocktool.config;

import com.lgy.httpmocktool.dao.GroovyRespJsonRepository;
import com.lgy.httpmocktool.service.SqlExecuteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;


import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.transaction.Transactional;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.stream.Stream;

@Slf4j
@Component
public class InitDbConfig {
    @Autowired
    private SqlExecuteService sqlExecuteService;
    @Autowired
    private GroovyRespJsonRepository groovyRepository;
    @Autowired
    private EntityManager em;

    @Bean(name = "InitDbConfig")
    public InitDbConfig initDbConfig() {
        initInsert();
        return new InitDbConfig();
    }

    /**
     * 初始化INSERT
     */
    public void initInsert() {
        executeSqlFile("insert.sql");
    }

    /**
     * 执行SQL文件
     * @param sqlFileName
     */

    public void executeSqlFile(String sqlFileName) {
        File file = new File(PathConfig.getDb() + File.separator + "sql" + File.separator + sqlFileName);
        try (FileReader fileReader = new FileReader(file);
             BufferedReader bufferedReader = new BufferedReader(fileReader)){
            Stream<String> lines = bufferedReader.lines();
            StringBuffer stringBuffer = new StringBuffer();
            lines.forEach(line -> {
                stringBuffer.append(line);
            });
            sqlExecuteService.executeSql(stringBuffer.toString());
//            int ddlFlag = jdbcTemplate.update(stringBuffer.toString());
//            log.info("DDL status : {}", ddlFlag);
        } catch (FileNotFoundException e) {
            log.error("找不到sql文件 : {}",sqlFileName , e);
        } catch (Exception e) {
            log.warn("{} 执行失败！！！", sqlFileName , e);
        }
    }

}
